Page({
  data: {
    goodsInfo: {},
    imgUrl: getApp().globalData.imgUrl,
    days: [],
    selectDayindex: 0,
    day: 30,//天数
    money: 0,//价格
    order_id: "",//订单号
    goods_rents: [],//天数对应的日租金
    buy_moneys: [],//天数对应的买断金
    attr: [],
    relet_scheme_id: '', // 续租方案id
    currentTerm: '', // 当前租期
    isAgree: false, // 是否同意合同
    parent_order_type: '',
    relet_order_total_rent: 0, // 共需要还款租金
    renewalOfLeaseData : [], // 期数列表
    relet_bill_list: [],  // 账单列表
    is_continue_relet: 0, // 是否继续续租
    disabledTerm: false, // 是否禁用期限
    termShow: false // 租期弹窗
  },
  onLoad(option) {
    my.setNavigationBar({
      frontColor: '#000000',
      backgroundColor: '#f6f6f6'
    })
    const { order_id, order_type, platform } = option
    let app = getApp();
    let vm = this;
    vm.setData({
      order_id,
      parent_order_type: order_type
    })
    if(platform) {
      app.globalData.platform = platform
    }
    // my.request({
    //   url: app.globalData.testUrl + '/Api/order/getGoodsTrem',
    //   method: 'POST',
    //   data: {
    //     order_id
    //   },
    //   dataType: 'json',
    //   success: function (res) {
    //     console.log('商品', res)
    //     if (res.data.status == '1001') {
    //       let _monthly_rent = parseFloat(res.data.data.goods[0].goods_rent);
    //       let _day = parseInt(res.data.data.goods[0].lease_period);

    //       vm.setData({
    //         imgUrl: app.globalData.imgUrl,
    //         goodsInfo: res.data.data,
    //         day: _day,
    //         money: (parseFloat(_day) * parseFloat(_monthly_rent)).toFixed(2)
    //       })

    //     }
    //   }
    // })
    my.request({
      url: `${app.globalData.testUrl}/api/relet/reletOrderConfirmInfo`,
      method: 'POST',
      data: {
        parent_order_id: order_id,
        parent_order_type: order_type,
        relet_scheme_id: '',
        zm_user_id: app.globalData.user_id
      },
      success: (res) => {
        const { data: { data, code, msg: content} } = res
        if(code !== 1) {
          my.showToast({
            type: 'none',
            content,
            duration: 1000
          })
        }
        let { 
          parent_order_info, 
          is_continue_relet, 
          relet_info: { 
            relet_scheme_id, 
            relet_terms,
            relet_order_total_rent,
            relet_way_title, relet_bill_list } 
          } = data

        parent_order_info.relet_way_title = relet_way_title
        this.setData({
          goodsInfo: parent_order_info,
        })
        if(is_continue_relet) {
          const renewalOfLeaseData = [{
            label: relet_terms + '期',
            value: relet_scheme_id
          }]
        
          this.setData({
            is_continue_relet,
            relet_scheme_id,
            renewalOfLeaseData,
            relet_bill_list,
            relet_order_total_rent,
            disabledTerm: true
          })
        }

      }
    })
  },

  // 阅读协议
  readAgreement(isAgree) {
    this.setData({
      isAgree
    })
  },

  // 获取账单列表
  getBillList() {
    let app = getApp();
    if(this.data.disabledTerm) return
    my.request({
      url: `${app.globalData.testUrl}/api/relet/getReletSchemesList`,
      method: 'POST',
      data: {
        relet_way: '1',
      },
      dataType: 'json',
      success: ({data: {data}}) => {
        const renewalOfLeaseData = data.map(({ id: value, relet_term: label}) => 
         {return {label: label + '期', value}}
        )
        console.log(renewalOfLeaseData, 'renewalOfLeaseData');
        this.setData({
          renewalOfLeaseData
        })
      }
    })
  },

  handleOk(e) {
    // this.setData({
    //   // termShow: true,
    //   relet_scheme_id: e
    // })
    // const term = this.data.renewalOfLeaseData.find(item => 
    //   item.value === e 
    // )
    // this.setData({
    //   currentTerm: term.label
    // })
  
    this.setData({
      relet_scheme_id: e
    })
    let app = getApp()
    const { order_id, parent_order_type } = this.data
    my.request({
      url: `${app.globalData.testUrl}/api/relet/reletOrderConfirmInfo`,
      method: 'POST',
      data: {
        parent_order_id: order_id,
        parent_order_type,
        relet_scheme_id: e + '',
        zm_user_id: app.globalData.user_id
      },
      success: ({data: {data, code, msg: content}}) => {
        if(code !== 1) {
          my.showToast({
            type: 'none',
            content,
            duration: 1000
          })
          return
        }
        const { 
          relet_info: {
            relet_order_total_rent,
            relet_bill_list
          }
        } = data
        this.setData({
          relet_order_total_rent,
          relet_bill_list
        })
      }
    })

  },
  onclickDay(e) {
    let _monthly_rent = parseFloat(e.currentTarget.dataset.value);
    let _day = parseInt(e.currentTarget.dataset.day);
    let _index = e.currentTarget.dataset.index;

    this.setData({
      day: _day,
      selectDayindex: _index,
      money: (parseFloat(_day) * parseFloat(_monthly_rent)).toFixed(2)
    })

  },
  // 提交续租
  keepOnRent() {
    const { 
      relet_scheme_id, 
      isAgree, 
      is_continue_relet,
      renewalOfLeaseData
    } = this.data
    if(!relet_scheme_id || !isAgree) {
      my.showToast({
        type: 'none',
        content: '请选择期数或续租合同须阅读同意！',
        duration: 2000,
      })
      return
    }

    // 继续续租没有弹窗，确认续租有弹窗
    if(!is_continue_relet) {
      const term = renewalOfLeaseData.find(item => 
        item.value === relet_scheme_id
      )
      this.setData({
        termShow: true,
        currentTerm: term.label
      })
      return
    }
    this.submitRent()
  },

  // 提交续租
  submitRent() {
    const { 
      relet_scheme_id, 
      order_id: parent_order_id, 
      parent_order_type,
    } = this.data
    let app = getApp()
    my.showLoading({
      content: '加载中...',
      delay: 0,
    });
    my.request({
      url: `${app.globalData.testUrl}/api/relet/confirmRelet`,
      method: 'POST',
      data: {
        parent_order_id,
        parent_order_type,
        relet_scheme_id: relet_scheme_id + '',
        zm_user_id: app.globalData.user_id
      },
      success: (res) => {
        let { data: { data, code, msg: content} } = res
        if(code !== 1) {
          my.showToast({
            type: 'none',
            content,
            duration: 3000
          })
          setTimeout(() => {
            my.hideLoading();
          }, 1000) 
          return
        }
        const { orderStr, relet_order_no, is_freeze_deposit } = data
        if(!is_freeze_deposit) {
          my.navigateTo({
            url: `/page/mine/myorders/renewalSuccess/renewalSuccess?relet_order_no=${relet_order_no}`
          })
          return
        }
        my.tradePay({
          orderStr,
          success: (res) => {
            const { resultCode: code } = res
            if(code === '9000') {
              my.showToast({
                type: 'none',
                content: '续租成功',
                duration: 1000,
                success: () => {
                  my.navigateTo({
                    url: `/page/mine/myorders/renewalSuccess/renewalSuccess?relet_order_no=${relet_order_no}`
                  })
                }
              })
            } else {
              setTimeout(() => {
                my.hideLoading();
              }, 1000) 
              my.showToast({
                type: 'none',
                content: '续租未完成',
                duration: 1000,
                success: () => {
                  my.navigateTo({
                    url: 
                    `/page/mine/myorders/renewalDetail/renewalDetail?parent_order_id=${parent_order_id}&parent_order_type=${parent_order_type}&relet_scheme_id=${relet_scheme_id}&relet_order_no=${relet_order_no}`
                  })
                }
              });
            }
          },
          fail: () => {
            setTimeout(() => {
              my.hideLoading();
            }, 1000) 
            my.showToast({
              type: 'none',
              content: '续租未完成',
              duration: 1000,
              success: () => {
                my.navigateTo({
                  url: 
                  `/page/mine/myorders/renewalDetail/
                  renewalDetail?parent_order_id=${parent_order_id}&parent_order_type=${parent_order_type}&relet_scheme_id=${relet_scheme_id}&relet_order_no=${relet_order_no}`
                })
              }
            })
          }
        })
      }
    })
  },

  // 确认
  confirm() {
    this.setData({
      termShow: false
    })
    this.submitRent()
  },

  // 取消
  cancel() {
    this.setData({
      termShow: false,
    })
  },
  // 查看合同
  queryContract() {
    let app = getApp();
    if (my.canIUse('web-view')) {
      my.downloadFile({
        url: app.globalData.imgUrl + "yonghuzulinxieyi.pdf",
        success({
          apFilePath
        }) {
          my.hideLoading();
          my.openDocument({
            filePath: apFilePath,
            fileType: 'pdf',
          })
        }
      })
    }
  },
  startAPVerify(options, callback) {//调起人脸识别
    my.call('startBizService', {
      name: 'open-certify',
      param: JSON.stringify(options),
    }, callback);
  },
  toGoodsDetail(e) {
    my.navigateTo({
      url: "../../../rent/goodsdetail/goodsdetail?id=" + e.currentTarget.dataset.goods_id
    })
  },
  jumpPage({target:{dataset: {url}}}) {
    my.navigateTo({
      url
    })
  }
});

